package server;

import java.util.ArrayList;
import java.util.Iterator;

import util.MyParser;

public class Game {
	private int winner;
	private ReceiveMonitor rm;
	private ArrayList<Participant> pl;
	private String currentWord;
	private int currentPainter;
	private ArrayList<ReceiveThread> rl;
	private TimerThread tm;
	private ReceiveMonitor serverrm;
	private int sessionID;
	private int time;
	private int remTime;

	public Game(ArrayList<Participant> pl, ReceiveMonitor rm,
			ReceiveMonitor serverrm, int sessionID, int time) {
		this.pl = pl;
		rl = new ArrayList<ReceiveThread>();
		this.rm = rm;
		this.serverrm = serverrm;
		this.sessionID = sessionID;
		this.time = time;
		remTime = 0;
	}

	public int run() {

		tm = new TimerThread(time, rm);
		tm.setPriority(6);
		tm.start();

		winner = -1;
		announceGameStart();

		while (winner == -1) {
			String input = rm.getMessage();
			Commands command = CommandParser.getGameCommands(input);
			int tempWriter = getIndex(MyParser.getName(input));
			switch (command) {
			case GAMEMESSAGE:
				if (MyParser.getMessage(input).equals("clear")) {
					ServerSend.serverGameSendToAll(pl, "clear");
				} else if (MyParser.getMessage(input).equals("leavegame")) {
					for (int i = 0; i < pl.size(); i++) {
						if (pl.get(i).getName().equals(MyParser.getName(input)))
							leaveGamePlayer(i);
					}
				}

				else {

				}
				break;
			case CHATMESSAGE:
				if (MyParser.getMessage(input).toLowerCase().contains(
						currentWord.toLowerCase())) {
					if (isCurrentPainter(tempWriter)) {
						ServerSend.sendToPlayer(pl, tempWriter,
								"Don't write the secret word!");
					} else {
						winner = tempWriter;
						chatSend(MyParser.indexToName(input, pl.get(tempWriter)
								.getName()));
						chatSend(pl.get(tempWriter).getName()
								+ " is the winner! The Correct word was: "
								+ currentWord);
						ServerSend.serverGameSendToAll(pl, "clear");
					}
				} else {
					chatSend(MyParser.indexToName(input, pl.get(tempWriter)
							.getName()));
				}
				break;
			case SERVERMESSAGE:
				if (MyParser.getMessage(input).equals("END")) {
					winner = SessionThread.TIME_OUT;
				}
				break;
			case PAINTMESSAGE:
				if (isCurrentPainter(tempWriter)) {
					paintSend(input);
				}
				break;
			case INVALID:
				break;
			}
		}

		if (winner != SessionThread.TIME_OUT
				&& winner != SessionThread.PAINTER_DISCONNECTED
				&& winner != SessionThread.NOT_ENOUGH_PLAYERS) {
			chatSend("The winner is " + pl.get(winner).getName());
		}
		if (winner == SessionThread.TIME_OUT) {
			chatSend("Time is up. The correct word was " + currentWord);
		}
		remTime = tm.getTime();
		tm.halt();
		return winner;
	}

	public void terminateThreads() {
		for (int i = 0; i < rl.size(); i++) {
			rl.get(i).stop();
		}
	}

	public void chatSend(String s) {
		for (int i = 0; i < pl.size(); i++) {
			ServerSend.sendToPlayer(pl, i, s);
		}
	}

	public void paintSend(String s) {
		for (int i = 0; i < pl.size(); i++) {
			if (!pl.get(i).equals(currentPainter)) {
				ServerSend.sendToPlayer(pl, i, s);
			}
		}
	}

	private boolean isCurrentPainter(int i) {
		return pl.get(i).equals(pl.get(currentPainter));
	}

	private int getIndex(String name) {
		Iterator<Participant> it = pl.iterator();
		int i = 0;
		while (it.hasNext()) {
			Participant temp = it.next();
			if (temp.getName().equals(name)) {
				return i;
			}
			i++;
		}
		return -1;
	}

	public int getTime() {
		return remTime;
	}

	public void setCurrentWord(String currentWord) {
		this.currentWord = currentWord;
	}

	public void setCurrentPainter(int currentPainter) {
		this.currentPainter = currentPainter;
	}

	public void leaveGamePlayer(int i) {
		String message = null;
		if (i == currentPainter && pl.size() > 2) {
			winner = SessionThread.PAINTER_DISCONNECTED;
			message = "The painter has left the game, new round starts!";

		} else if (pl.size() == 2) {
			winner = SessionThread.NOT_ENOUGH_PLAYERS;
			message = "Not enough players left!";
		} else {
			if (i < currentPainter) {
				winner = SessionThread.UPDATE_PAINTER;
			}
			message = pl.get(i).getName() + " has left the game!";
		}
		serverrm.setMessage(MyParser.SERVER + MyParser.FIELD + "exitgame"
				+ MyParser.FIELD + sessionID, pl.get(i).getName());
		chatSend(message);
	}

	public void announcePainter() {
		String s;

		if (currentPainter > (pl.size() - 1)) {
			currentPainter = 0;
		}
		for (int i = 0; i < pl.size(); i++) {
			if (i == currentPainter) {
				s = MyParser.codeToChat(
						"You are the PaintMaster!\nYou shall paint: "
								+ currentWord, "server");
				ServerSend.sendToPlayer(pl, i, MyParser
						.codeToGame("paintmaster"));
				ServerSend.sendToPlayer(pl, currentPainter, MyParser
						.codeToGame("word" + MyParser.FIELD + currentWord));
			} else {

				s = MyParser.codeToChat(pl.get(currentPainter).getName()
						+ " is the PaintMaster!", "server");
			}
			ServerSend.sendToPlayer(pl, i, s);
		}
	}

	public void announceGameStart() {
		ServerSend.serverGameSendToAll(pl, "time" + MyParser.FIELD + time);
		announcePainter();
	}
}
